package com.ruoyi.functiontest.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.functiontest.mapper.InterchangeMileageStatTestMapper;
import com.ruoyi.functiontest.domain.InterchangeMileageStatTest;
import com.ruoyi.functiontest.service.IInterchangeMileageStatTestService;
import com.ruoyi.function.domain.InterchangeMileageStat;
import com.ruoyi.function.service.IInterchangeMileageStatService;

/**
 * 互通里程实测数据测试Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class InterchangeMileageStatTestServiceImpl implements IInterchangeMileageStatTestService 
{
    @Autowired
    private InterchangeMileageStatTestMapper interchangeMileageStatTestMapper;
    
    @Autowired
    private IInterchangeMileageStatService interchangeMileageStatService;

    /**
     * 查询互通里程实测数据测试
     * 
     * @param id 互通里程实测数据测试主键
     * @return 互通里程实测数据测试
     */
    @Override
    public InterchangeMileageStatTest selectInterchangeMileageStatTestById(Long id)
    {
        return interchangeMileageStatTestMapper.selectInterchangeMileageStatTestById(id);
    }

    /**
     * 查询互通里程实测数据测试列表
     * 
     * @param interchangeMileageStatTest 互通里程实测数据测试
     * @return 互通里程实测数据测试
     */
    @Override
    public List<InterchangeMileageStatTest> selectInterchangeMileageStatTestList(InterchangeMileageStatTest interchangeMileageStatTest)
    {
        return interchangeMileageStatTestMapper.selectInterchangeMileageStatTestList(interchangeMileageStatTest);
    }

    /**
     * 新增互通里程实测数据测试
     * 
     * @param interchangeMileageStatTest 互通里程实测数据测试
     * @return 结果
     */
    @Override
    public int insertInterchangeMileageStatTest(InterchangeMileageStatTest interchangeMileageStatTest)
    {
        return interchangeMileageStatTestMapper.insertInterchangeMileageStatTest(interchangeMileageStatTest);
    }

    /**
     * 修改互通里程实测数据测试
     * 
     * @param interchangeMileageStatTest 互通里程实测数据测试
     * @return 结果
     */
    @Override
    public int updateInterchangeMileageStatTest(InterchangeMileageStatTest interchangeMileageStatTest)
    {
        return interchangeMileageStatTestMapper.updateInterchangeMileageStatTest(interchangeMileageStatTest);
    }

    /**
     * 批量删除互通里程实测数据测试
     * 
     * @param ids 需要删除的互通里程实测数据测试主键
     * @return 结果
     */
    @Override
    public int deleteInterchangeMileageStatTestByIds(Long[] ids)
    {
        return interchangeMileageStatTestMapper.deleteInterchangeMileageStatTestByIds(ids);
    }

    /**
     * 删除互通里程实测数据测试信息
     * 
     * @param id 互通里程实测数据测试主键
     * @return 结果
     */
    @Override
    public int deleteInterchangeMileageStatTestById(Long id)
    {
        return interchangeMileageStatTestMapper.deleteInterchangeMileageStatTestById(id);
    }

    @Override
    public boolean hasChildById(Long id)
    {
        return interchangeMileageStatTestMapper.hasChildById(id) > 0;
    }
    
    @Override
    public String importInterchangeMileageStatTest(List<InterchangeMileageStatTest> importList, boolean updateSupport)
    {
        if (importList == null || importList.isEmpty()) {
            return "导入数据不能为空！";
        }
        
        int successCount = 0;
        int failureCount = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        // 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
        for (InterchangeMileageStatTest data : importList) {
            try {
                // 基本数据验证
                if (data.getRoadName() == null) {
                    data.setRoadName("");
                }
                
                // 通过id和parentid来确定数据
                InterchangeMileageStatTest existingData = null;
                
                // 使用新的方法通过id和parentid组合来精确匹配数据
                InterchangeMileageStatTest query = new InterchangeMileageStatTest();
                query.setId(data.getId());
                query.setParentId(data.getParentId());
                
                List<InterchangeMileageStatTest> existingList = interchangeMileageStatTestMapper.selectInterchangeMileageStatTestByIdAndParentId(query);
                if (existingList != null && !existingList.isEmpty()) {
                    existingData = existingList.get(0);
                }
                
                if (existingData != null) {
                    // 已存在节点，如果支持更新则更新
                    if (updateSupport) {
                        existingData.setRoadName(data.getRoadName());
                        existingData.setNodeName(data.getNodeName());
                        existingData.setRamp1Type(data.getRamp1Type());
                        existingData.setRamp1Length(data.getRamp1Length());
                        existingData.setRamp2Type(data.getRamp2Type());
                        existingData.setRamp2Length(data.getRamp2Length());
                        existingData.setRamp3Type(data.getRamp3Type());
                        existingData.setRamp3Length(data.getRamp3Length());
                        existingData.setRamp4Type(data.getRamp4Type());
                        existingData.setRamp4Length(data.getRamp4Length());
                        existingData.setRampAvgLength(data.getRampAvgLength());
                        existingData.setTollCenterLength(data.getTollCenterLength());
                        existingData.setApproachLength(data.getApproachLength());
                        existingData.setRemark(data.getRemark());
                        existingData.setParentId(data.getParentId());
                        
                        interchangeMileageStatTestMapper.updateInterchangeMileageStatTest(existingData);
                        successCount++;
                    } else {
                        // 不支持更新，跳过此条数据
                        failureCount++;
                        failureMsg.append("<br/>" + failureCount + ". 数据已存在，跳过: " + data.getRoadName() + "-" + data.getNodeName());
                    }
                } else {
                    // 不存在节点，创建新节点
                    InterchangeMileageStatTest newNode = new InterchangeMileageStatTest();
                    newNode.setId(data.getId()); // 使用Excel中的id值
                    newNode.setRoadName(data.getRoadName());
                    newNode.setNodeName(data.getNodeName());
                    newNode.setRamp1Type(data.getRamp1Type());
                    newNode.setRamp1Length(data.getRamp1Length());
                    newNode.setRamp2Type(data.getRamp2Type());
                    newNode.setRamp2Length(data.getRamp2Length());
                    newNode.setRamp3Type(data.getRamp3Type());
                    newNode.setRamp3Length(data.getRamp3Length());
                    newNode.setRamp4Type(data.getRamp4Type());
                    newNode.setRamp4Length(data.getRamp4Length());
                    newNode.setRampAvgLength(data.getRampAvgLength());
                    newNode.setTollCenterLength(data.getTollCenterLength());
                    newNode.setApproachLength(data.getApproachLength());
                    newNode.setRemark(data.getRemark());
                    newNode.setParentId(data.getParentId());
                    
                    interchangeMileageStatTestMapper.insertInterchangeMileageStatTest(newNode);
                    successCount++;
                }
                
            } catch (Exception e) {
                failureCount++;
                String msg = "<br/>" + failureCount + ". 导入失败：";
                if (data.getRoadName() != null) {
                    msg += "路段名称：" + data.getRoadName();
                }
                if (data.getNodeName() != null) {
                    msg += "，收费站互通名称：" + data.getNodeName();
                }
                failureMsg.append(msg + e.getMessage());
            }
        }
        
        if (failureCount > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureCount + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successCount + " 条，数据已导入到系统。");
            return successMsg.toString();
        }
    }
    
    @Override
    public int updateReview1ToZero()
    {
        return interchangeMileageStatTestMapper.updateReview1ToZero();
    }
    
    @Override
    public boolean checkAllReview1IsZero()
    {
        return interchangeMileageStatTestMapper.checkAllReview1IsZero() == 0;
    }
    
    @Override
    public int updateReview2ToZeroByCondition(InterchangeMileageStatTest queryCondition)
    {
        return interchangeMileageStatTestMapper.updateReview2ToZeroByCondition(queryCondition);
    }
    
    @Override
    public boolean checkAllReview1AndReview2AreZero()
    {
        return interchangeMileageStatTestMapper.checkAllReview1AndReview2AreZero() == 0;
    }
    
    @Override
    public int updateReview3ToZero()
    {
        return interchangeMileageStatTestMapper.updateReview3ToZero();
    }
    
    /**
     * 检查所有数据的review1、review2和review3是否为0，并将数据同步到正式表
     * 
     * @return 同步结果信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String syncDataToInterchangeMileageStat()
    {
        // 检查是否有未审核通过的数据
        int notZeroCount = interchangeMileageStatTestMapper.countReview1OrReview2OrReview3NotZero();
        if (notZeroCount > 0) {
            return "同步失败：存在未审核通过的数据，请确保所有数据的review1、review2和review3字段都为0";
        }
        
        // 查询所有测试表数据
        List<InterchangeMileageStatTest> testDataList = interchangeMileageStatTestMapper.selectInterchangeMileageStatTestList(new InterchangeMileageStatTest());
        
        int insertCount = 0;
        int updateCount = 0;
        
        // 遍历测试表数据，同步到正式表
        for (InterchangeMileageStatTest testData : testDataList) {
            InterchangeMileageStat formalData = new InterchangeMileageStat();
            
            // 复制字段数据（除了review1、review2、review3）
            formalData.setId(testData.getId());
            formalData.setParentId(testData.getParentId());
            formalData.setRoadName(testData.getRoadName());
            formalData.setNodeName(testData.getNodeName());
            formalData.setRamp1Type(testData.getRamp1Type());
            formalData.setRamp1Length(testData.getRamp1Length());
            formalData.setRamp2Type(testData.getRamp2Type());
            formalData.setRamp2Length(testData.getRamp2Length());
            formalData.setRamp3Type(testData.getRamp3Type());
            formalData.setRamp3Length(testData.getRamp3Length());
            formalData.setRamp4Type(testData.getRamp4Type());
            formalData.setRamp4Length(testData.getRamp4Length());
            formalData.setRampAvgLength(testData.getRampAvgLength());
            formalData.setTollCenterLength(testData.getTollCenterLength());
            formalData.setApproachLength(testData.getApproachLength());
            formalData.setRemark(testData.getRemark());
            formalData.setDeptId(testData.getDeptId());
            formalData.setRoleId(testData.getRoleId());
            
            // 检查正式表中是否存在相同id和parentId的数据
            InterchangeMileageStat query = new InterchangeMileageStat();
            query.setId(testData.getId());
            query.setParentId(testData.getParentId());
            InterchangeMileageStat existingData = interchangeMileageStatService.selectInterchangeMileageStatByIdAndParentId(query);
            
            if (existingData != null) {
                // 更新现有数据
                interchangeMileageStatService.updateInterchangeMileageStat(formalData);
                updateCount++;
            } else {
                // 插入新数据
                interchangeMileageStatService.insertInterchangeMileageStat(formalData);
                insertCount++;
            }
        }
        
        return "同步成功：新增 " + insertCount + " 条记录，更新 " + updateCount + " 条记录";
    }
}
